package com.jnchen.jwt.impl;

import com.jnchen.jwt.api.JwtInterface;
import com.jnchen.jwt.entity.User;
import com.jnchen.jwt.util.RsaUtil;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.JWTOptions;
import io.vertx.ext.jwt.JWK;
import io.vertx.ext.jwt.JWT;

import java.security.KeyPair;
import java.util.Base64;

/**
 * vertx jwt 实现
 *
 * @author jnchen
 * @date 2020/10/30 11:26
 */
public class VertxImpl implements JwtInterface {
    private static final JWK JWK;
    private static final String ALGORITHM = "RS512";

    static {
        KeyPair pair = RsaUtil.getRsaKey();
        JWK = new JWK(ALGORITHM,
                Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()),
                Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
    }

    @Override
    public String createJwt(User user, long expireIn) {
        JWT jwt = new JWT().addJWK(JWK);
        JWTOptions options = new JWTOptions();
        options.setAlgorithm(ALGORITHM);
        options.setExpiresInSeconds((int) (expireIn / 1000));
        JsonObject payload = new JsonObject();
        payload.put("id", user.getId());
        payload.put("name", user.getName());
        payload.put("operations", user.getOperations());
        return jwt.sign(payload, options);
    }

    @Override
    @SuppressWarnings("unchecked")
    public User parseJwt(String token) {
        JsonObject jsonObject = new JWT().addJWK(JWK).decode(token);
        User user = new User();
        user.setId(jsonObject.getInteger("id"));
        user.setName(jsonObject.getString("name"));
        user.setOperations(jsonObject.getJsonArray("operations").getList());
        return user;
    }

    @Override
    public boolean checkJwt(String token) {
        JWT verifier = new JWT().addJWK(JWK);
        try {
            verifier.decode(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
